﻿using AutoMapper;
using B.S.Packaged.Domain;
using B.S.Packaged.ErrorCode;
using B.S.Packaged.WebAPI.Write.Applications.Commands.MaterialPreparation;
using MediatR;
using SqlSugar;

namespace B.S.Packaged.WebAPI.Write.Applications.CommandHandlers
{
    public class AddMaterialPreparationHander : IRequestHandler<AddMaterialPreparationCommand, APIResult<int>>
    {
        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public AddMaterialPreparationHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 添加物料备料操作
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<int>> Handle(AddMaterialPreparationCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var entity = mapper.Map<Domain.MaterialPreparation>(request);
            var one = db.Queryable<Domain.MaterialPreparation>().Where(x => x.ItemName == request.ItemName).First();

            if (one != null)
            {
                result.code = APIResultCode.noname;
                result.msg = APIResultCode.noname.ToString();
                result.data = 0;
                return await Task.FromResult(result);
            }

            var insertResult = await db.Insertable<Domain.MaterialPreparation>(entity).ExecuteReturnIdentityAsync();

            if (insertResult > 0)
            {
                result.code = APIResultCode.success;
                result.msg = APIResultCode.success.ToString();
                result.data = insertResult;

                // 添加成功后，根据添加记录的 ID 更新 PackagingPlan 表的 preparation 值
                try
                {
                    var updateResult = await db.Updateable<PackagingPlan>()
                        .SetColumns(x => x.Preparation == true)
                        .Where(x => x.PackagingPlanId == request.PackagingPlanId)
                        .ExecuteCommandAsync();

                    if (updateResult <= 0)
                    {
                        // 这里可以记录日志，提示更新 PackagingPlan 表失败
                    }
                }
                catch (Exception ex)
                {
                    // 处理更新过程中的异常，这里可以记录日志
                }
            }
            else
            {
                result.code = APIResultCode.failed;
                result.msg = APIResultCode.failed.ToString();
                result.data = insertResult;
            }

            return await Task.FromResult(result);
        }
    }
}